package com.boken.caelum.common.service;

import com.boken.caelum.common.mybatis.model.ModelExample;
import com.github.pagehelper.PageHelper;
import tk.mybatis.mapper.common.Mapper;

import java.util.Collections;
import java.util.List;


public abstract class BaseServiceImpl<M, E extends ModelExample> implements BaseService<M, E> {

	protected Mapper<M> mapper;

	@Override
	public int countByExample(E example) {
		return mapper.selectCountByExample(example);
	}

	@Override
	public int deleteByExample(E example) {
		return mapper.deleteByExample(example);
	}

	@Override
	public int deleteByPrimaryKey(Object id) {
		return mapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(M model) {
		int flag = mapper.insert(model);
		return flag;
	}

	@Override
	public int insertSelective(M model) {
		int flag = mapper.insertSelective(model);
		return flag;
	}

	@Override
	public List<M> selectByExample(E example) {
		List<M> list = mapper.selectByExample(example);
		if (list == null) {
			list = Collections.emptyList();
		}
		return list;
	}

	@Override
	public M selectByPrimaryKey(Object id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public M selectOneByExample(E example) {
		example.setLimit(1);
		example.setOffset(0);
		List<M> list = selectByExample(example);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public int updateByExampleSelective(M model, E example) {
		return mapper.updateByExampleSelective(model, example);
	}

	@Override
	public int updateByPrimaryKeySelective(M model) {
		return mapper.updateByPrimaryKeySelective(model);
	}

	@Override
	public int updateByExample(M model, E example) {
		return mapper.updateByExample(model, example);
	}

	@Override
	public int updateByPrimaryKey(M model) {
		return mapper.updateByPrimaryKey(model);
	}

	@Override
	public List<M> selectPageByExample(Integer pageNum, Integer pageSize, E example){
		pageNum = pageNum == null ? 1 : pageNum;
		pageSize = pageSize == null ? 10 : pageSize;
		PageHelper.startPage(pageNum, pageSize);
		List<M> list = selectByExample(example);
		return list;
	}
}
